package com.shankungfu.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.L;
import com.shankungfu.GlobleConstant;
import com.shankungfu.R;
import com.shankungfu.baidu.BaiDuUtils;
import com.shankungfu.bean.PickItemBean;
import com.shankungfu.main.AboutUsActivity;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.PushMessageKeeper;
import com.shankungfu.util.TestUtils;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;
import com.shankungfu.view.CustomDialog;
import com.shankungfu.view.CustomDialog.Builder;

public class SettingFragment extends Fragment implements OnClickListener {
	private RelativeLayout about_us;
	private RelativeLayout mark_score;
	private RelativeLayout contact_us;
	private RelativeLayout check_update;
	private CheckBox push_switch;
	private RelativeLayout clear_data;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.setting_layout, null);

		init(v);

		return v;
	}

	private void init(View v) {
		about_us = (RelativeLayout) v.findViewById(R.id.about_us);
		mark_score = (RelativeLayout) v.findViewById(R.id.mark_score);
		contact_us = (RelativeLayout) v.findViewById(R.id.contact_us);
		check_update = (RelativeLayout) v.findViewById(R.id.check_update);
		clear_data = (RelativeLayout) v.findViewById(R.id.clear_data);
		push_switch = (CheckBox) v
				.findViewById(R.id.message_notifcation_switch);

		push_switch.setOnClickListener(this);
		about_us.setOnClickListener(this);
		mark_score.setOnClickListener(this);
		contact_us.setOnClickListener(this);
		check_update.setOnClickListener(this);
		clear_data.setOnClickListener(this);

		changeSwitch();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.about_us:
			startActivity(new Intent(getActivity(), AboutUsActivity.class));
			break;
		case R.id.mark_score:
			Uri uri = Uri.parse("market://details?id="
					+ getActivity().getPackageName());
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			break;
		case R.id.clear_data:
			showClearDialog();
			break;
		case R.id.contact_us:
			try {
				Intent data = new Intent(Intent.ACTION_SENDTO);
				data.setData(Uri.parse("mailto:support@shankungfu.org"));
				data.putExtra(Intent.EXTRA_SUBJECT, "反馈");
				data.putExtra(Intent.EXTRA_TEXT,
						"您想跟我们说些什么呢？欢迎你的反馈和建议，我们会认真考虑!");
				startActivity(data);
			} catch (Exception e) {
				e.printStackTrace();
				ToastUtil.showMessageText(getActivity(), "你的手机没有安装邮件客户端！");
			}
			break;
		case R.id.check_update:
			getData();
			break;
		case R.id.message_notifcation_switch: // 推送控制开关
			if (push_switch.isChecked()) { // 开

				if (PushManager.isPushEnabled(getActivity().getApplication())) {
					PushManager.startWork(
							getActivity().getApplicationContext(),
							PushConstants.LOGIN_TYPE_API_KEY,
							BaiDuUtils.getMetaValue(getActivity(), "api_key"));
				} else {
					PushManager.resumeWork(getActivity().getApplication());
				}

				PushMessageKeeper.keepPushMessage(getActivity()
						.getApplicationContext(), true);
				L.d("push_switch 的状态是： "
						+ PushMessageKeeper.readPushMessage(getActivity()));
			} else { // 关
				PushManager.stopWork(getActivity().getApplication());
				PushMessageKeeper.keepPushMessage(getActivity()
						.getApplicationContext(), false);
				L.d("push_switch 的状态是： "
						+ PushMessageKeeper.readPushMessage(getActivity()));
			}
			break;

		default:
			break;
		}
	}

	private void getData() {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "upgrade");
		params.add("device", "android");
		params.add("version", getVersionName());
		MyAsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {

					HasNewBean dataBean = JSON.parseObject(content, HasNewBean.class);

					float oldVersion = Float.valueOf(getVersionName());
					float newVersion = Float.valueOf(dataBean.getUpgradeData()
							.getVersion_name());

					if (oldVersion < newVersion) {
						CustomDialog.Builder builder = new Builder(
								getActivity());
						builder.setTitle(R.string.update_app);
						builder.setMessage(R.string.update_content);
						builder.setPositiveButton(R.string.confirm,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {

										Intent intent = new Intent();
										intent.setAction("android.intent.action.VIEW");
										Uri content_url = Uri
												.parse("http://www.cnblogs.com");
										intent.setData(content_url);
										startActivity(intent);

										dialog.dismiss();
									}
								});
						builder.setNegativeButton(R.string.cancel,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
						builder.create().show();
					} else {
						ToastUtil.showMessageText(getActivity(), "你的版本已经是最新的版");
					}
				} else {
					ToastUtil.showMessageText(getActivity(), "更新失败,请重新尝试");
				}
			}

			@Override
			public void onFailure(String content) {
				ToastUtil.showMessageText(getActivity(), "你的版本已经是最新的版");
			}
		};
		responseHandler.setShowNotNetToast(false);
		httpclient.request(GlobleConstant.HAS_NEW, params, responseHandler);
	}

	private String getVersionName(){
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			// 获取packagemanager的实例
			PackageManager packageManager = getActivity().getPackageManager();
			packInfo = packageManager.getPackageInfo(getActivity()
					.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (packInfo == null) {
			return "0";
		}
		String version = packInfo.versionName;
		return version;
	}

	/**
	 * 改变里面的开关选项 WangQing 2013-8-19 void
	 */
	private void changeSwitch() {

		boolean pushSwitch = com.shankungfu.util.PushMessageKeeper
				.readPushMessage(getActivity().getApplication());
		if (pushSwitch) {
			push_switch.setChecked(true);
		} else {
			push_switch.setChecked(false);
		}

	}

	private void showClearDialog() {
		CustomDialog.Builder builder = new Builder(getActivity());
		builder.setMessage("你确定要清除缓存吗?");
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				ImageLoader loader = ImageLoader.getInstance();
				loader.clearDiscCache();
				loader.clearMemoryCache();

				dialog.dismiss();
				ToastUtil.showMessageText(getActivity(), "清除缓存完毕");
			}
		});
		builder.create().show();
	}

}
